package com.rocpenghua.codec;

import com.rocpenghua.codec.sm4Simple.HexUtil;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

/**
 * @author pengp
 * @date 2022年04月19日 17:00
 */
public class OracleDesUtil {
    private OracleDesUtil() {
    }
    public static String DES_KEY_VALUE = "QAZXSW!@#123654*";
    private final static String DES = "DES";
    private final static String CIPHER_DES = "DES/CBC/NoPadding";

    /**
     *
     * @param data 数据
     * @param key 密钥
     * @return
     */
    public static String encrypt(String data, String key) {
        try {
            DESKeySpec desKey = new DESKeySpec(key.getBytes());
            SecretKey securekey = SecretKeyFactory.getInstance(DES).generateSecret(desKey);

            Cipher cipher = Cipher.getInstance(CIPHER_DES);
            cipher.init(Cipher.ENCRYPT_MODE, securekey, new IvParameterSpec(new byte[8]));

            byte[] inBytes = new byte[((int) (data.length() / 8) + 1) * 8];
            for (int i = 0; i < data.length(); i++) {
                inBytes[i] = data.getBytes()[i];
            }

            byte[] enBytes = cipher.doFinal(inBytes);
            //base64
            //return Base64.encodeBase64String(enBytes);
            //hex
            return HexUtil.getHexString(enBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String decrypt(String data, String key) {
        try {
            DESKeySpec desKey = new DESKeySpec(key.getBytes());
            SecretKey secretKey = SecretKeyFactory.getInstance(DES).generateSecret(desKey);

            Cipher cipher = Cipher.getInstance(CIPHER_DES);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(new byte[8]));
            //base64
            //byte[]decryptBytes = cipher.doFinal(Base64.decodeBase64(data));
            //hex
            byte[]decryptBytes = cipher.doFinal(HexUtil.hexStringToBytes(data));

            return new String(decryptBytes);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
